package com.liang.security.springboot.service;

import com.liang.security.springboot.dao.UserDao;
import com.liang.security.springboot.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liang zai
 * @date 2021/9/1 17:38
 * @description
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto userDto = userDao.getUserByName(username);
        if (userDto == null) {
            //如果用户查询不到，返回null，由provider来抛出异常
            return null;
        }
        //根据用户的id去查找用户的权限
        List<String> perms = userDao.findPermissionsByUserId(userDto.getId());
        String[] permsArray = new String[perms.size()];
        perms.toArray(permsArray);
        UserDetails details = User
                .withUsername(userDto.getUsername())
                .password(userDto.getPassword())
                .authorities(perms.toArray(permsArray)).build();
        return details;
    }
}
